package com.example.reflect;

import java.lang.reflect.Field;

public class ExtendsFieldsTests {
    private static class Parent {
        private String parentName;

        public Parent(String parentName) {
            this.parentName = parentName;
        }

        @Override
        public String toString() {
            return "Parent{" +
                    "parentName='" + parentName + '\'' +
                    '}';
        }
    }

    private static class Son extends ExtendsFieldsTests.Parent {
        private String sonName;

        public Son(String parentName, String sonName) {
            super(parentName);
            this.sonName = sonName;
        }

        @Override
        public String toString() {
            return "Son{" +
                    "sonName='" + sonName + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        // 结论：通过子类的Class对象无法直接获取到父类的private字段
        // Field parentName = ExtendsFieldsTests.Son.class.getField("parentName");
        // Field parentName = ExtendsFieldsTests.Son.class.getDeclaredField("parentName");

        // 但是可以通过getSuperclass方法获取父类的Class对象来间接获取这个私有字段
        Class<? super Son> superclass = Son.class.getSuperclass();
        Field parentName = superclass.getDeclaredField("parentName");

        parentName.setAccessible(true);
        ExtendsFieldsTests.Son son = new ExtendsFieldsTests.Son("父类", "子类");
        Object o = parentName.get(son);
        System.out.println(o);
    }
}
